<template>
  <div class="contractAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <!-- v-if="!contactAddShow" -->
      <el-button
        v-if="pageType === 'check'"
        class="btn save"
        @click="handleCheckBtn2(contractFormRef, 3, '同意')"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >同意</el-button
      >
      <el-button
        v-if="pageType === 'check'"
        class="btn withdraw"
        @click="handleCheckBtn2(contractFormRef, 4, '拒绝')"
        ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
        >拒绝</el-button
      >

      <el-button
        v-if="pageType === 'check'"
        class="btn withdraw"
        @click="handleCheckBtn2(contractFormRef, 6, '驳回')"
        ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
        >驳回</el-button
      >
      <el-button
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="btn submit"
        @click="handleAddSave(contractFormRef, 1)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >提交</el-button
      >
      <el-button
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="btn save"
        @click="handleAddSave(contractFormRef, 0)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >存为草稿</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon"> <Back /> </el-icon>返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-show="!contactAddShow"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType == "detail" || pageType == "check"
                ? ""
                : pageType === "add"
                ? "新增"
                : "编辑"
            }}合同信息</span
          >
        </template>
        <div class="contract-info">
          <el-form
            :model="contractForm"
            ref="contractFormRef"
            :rules="queryRules"
            label-width="120px"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="合同编号：">
                  <el-input
                    v-model="contractForm.contractCode"
                    placeholder="自动生成"
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同名称：" prop="contractName">
                  <el-input
                  maxlength="50"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.contractName"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="是否已实施：">
                  <el-select
                    v-model="contractForm.implementation"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                    disabled
                  >
                    <el-option
                      v-for="dict in impleList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="业务人员：" prop="userId">
                  <el-select
                    :disabled="pageType === 'check'"
                    v-model="contractForm.userId"
                    style="width: 268px"
                    placeholder="请选择"
                    clearable
                    filterable
                    popper-class="custom-dropdown"
                    placement="bottom-end"
                    @change="handlePeopleChange"
                  >
                    <div class="dropdown-slot">
                      <span
                        style="
                          float: left;
                          color: #8492a6;
                          margin: 0 0px 0 20px;
                        "
                        >人员姓名</span
                      >
                      <span style="margin: 0 90px 0 57px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </div>
                    <div class="scrollable-options">
                      <el-option
                        v-for="item in userList"
                        :key="item.userId"
                        :label="item.nickName"
                        :value="item.userId"
                      >
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            float: left;
                            color: #8492a6;
                          "
                          >{{ item.nickName }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 15px 0 23px;
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          >{{
                            item.phonenumber ? item.phonenumber : "--"
                          }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            font-size: 13px;
                            margin: 0 0px 0 0px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.postName ? item.postName : "--" }}
                        </span>
                        <span
                          style="
                            display: inline-block;
                            margin: 0 0px 0 0px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.deptName ? item.deptName : "--" }}
                        </span>
                      </el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="甲方单位：" prop="firstCompanyId">
                  <el-select
                    :disabled="pageType === 'check'"
                    v-model="contractForm.firstCompanyId"
                    style="width: 268px"
                    placeholder="请选择"
                    clearable
                    popper-class="custom-dropdown"
                  >
                    <div class="dropdown-slot">
                      <span
                        style="
                          float: left;
                          color: #8492a6;
                          margin: 0 0px 0 20px;
                        "
                        >客户编号</span
                      >
                      <span style="margin: 0 34px 0 54px; color: #8492a6"
                        >客户名称</span
                      >
                      <span
                        style="
                          margin: 0 78px 0 54px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >企业法人</span
                      >
                      <span style="color: #8492a6; font-size: 13px"
                        >业务人员</span
                      >
                    </div>
                    <div class="scrollable-options">
                      <el-option
                        v-for="item in customerList"
                        :key="item.customerId"
                        :label="item.name"
                        :value="item.customerId"
                      >
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            float: left;
                            color: #8492a6;
                          "
                          >{{ item.customerNum }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 15px 0 23px;
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          >{{ item.name ? item.name : "--" }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            font-size: 13px;
                            margin: 0 0px 0 0px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.legalPerson }}
                        </span>
                        <span
                          style="
                            display: inline-block;
                            margin: 0 0px 0 0px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.userName }}
                        </span>
                      </el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户单位：" prop="secondCompanyId">
                  <el-select
                    :disabled="pageType === 'check'"
                    v-model="contractForm.secondCompanyId"
                    style="width: 268px"
                    placeholder="请选择"
                    clearable
                    popper-class="custom-dropdown"
                  >
                    <div class="dropdown-slot">
                      <span
                        style="
                          float: left;
                          color: #8492a6;
                          margin: 0 0px 0 20px;
                        "
                        >客户编号</span
                      >
                      <span style="margin: 0 34px 0 54px; color: #8492a6"
                        >客户名称</span
                      >
                      <span
                        style="
                          margin: 0 78px 0 54px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >企业法人</span
                      >
                      <span style="color: #8492a6; font-size: 13px"
                        >业务人员</span
                      >
                    </div>
                    <div class="scrollable-options">
                      <el-option
                        v-for="item in customerList"
                        :key="item.customerId"
                        :label="item.name"
                        :value="item.customerId"
                      >
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            float: left;
                            color: #8492a6;
                          "
                          >{{ item.customerNum }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 15px 0 23px;
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          >{{ item.name ? item.name : "--" }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            font-size: 13px;
                            margin: 0 0px 0 0px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.legalPerson }}
                        </span>
                        <span
                          style="
                            display: inline-block;
                            margin: 0 0px 0 0px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.userName }}
                        </span>
                      </el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否续签：" prop="renew">
                  <el-select
                    :disabled="pageType === 'check'"
                    v-model="contractForm.renew"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleRenewChange"
                  >
                    <el-option
                      v-for="dict in flagList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同类型：" prop="contractKind">
                  <el-select
                    :disabled="contractForm.renew == 1 || pageType === 'check'"
                    v-model="contractForm.contractKind"
                    placeholder="请选择"
                    @change="handleApplyTypeChange"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in contractKindList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 0:销售合同；1：补充协议；2：解除协议 -->

              <el-col
                :span="6"
                v-if="
                  contractForm.contractKind == 1 ||
                  contractForm.contractKind == 2 ||
                  contractForm.contractKind == 3 ||
                  contractForm.renew == 1
                "
              >
                <el-form-item label="原合同：" prop="oldContractId">
                  <el-select
                    :disabled="pageType === 'check'"
                    v-model="contractForm.oldContractId"
                    class="search-input"
                    placeholder="请选择"
                    clearable
                    @change="handlecontractschange"
                    :placement="'bottom-start'"
                  >
                    <template v-if="contractList.length">
                      <el-option disabled :value="{}">
                        <div class="auto-top">
                          <span class="auto-item">合同编号</span>
                          <span class="auto-item">合同名称</span>
                          <span class="auto-item">甲方单位</span>
                        </div>
                      </el-option>
                      <el-option
                        v-for="dict in contractList"
                        :key="dict.contractId"
                        :label="dict.contractName"
                        :value="dict.contractId"
                      >
                        <div style="display: flex">
                          <div class="auto-item" :title="dict.contractCode">
                            {{ dict.contractCode }}
                          </div>
                          <div class="auto-item" :title="dict.contractName">
                            {{ dict.contractName }}
                          </div>
                          <div class="auto-item" :title="dict.firstParty">
                            {{ dict.firstParty }}
                          </div>
                        </div>
                      </el-option>
                    </template>

                    <template v-else>
                      <el-option
                        v-for="dict in []"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="关联项目：" prop="projectIds">
                  <el-select
                    :disabled="
                      pageType === 'check' ||
                      contractForm.renew == 1 ||
                      contractForm.contractKind == 1 ||
                      contractForm.contractKind == 3
                    "
                    v-model="contractForm.projectIds"
                    class="search-input"
                    style="height: 100%"
                    placeholder="请选择"
                    clearable
                    multiple
                    popper-class="custom-dropdown"
                    :placement="'bottom'"
                    @change="handleprojectIdschange"
                  >
                    <div class="dropdown-slot">
                      <span
                        style="
                          float: left;
                          color: #8492a6;
                          margin: 0 0px 0 20px;
                        "
                        >项目编号</span
                      >
                      <span style="margin: 0 90px 0 105px; color: #8492a6"
                        >项目名称</span
                      >
                      <span
                        style="
                          margin: 0 50px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >项目类别</span
                      >
                      <span style="color: #8492a6; font-size: 13px"
                        >项目类型</span
                      >
                    </div>
                    <div class="scrollable-options">
                      <el-option
                        v-for="item in projectList"
                        :key="item.projectId"
                        :label="item.projectName"
                        :value="item.projectId"
                      >
                        <span
                          style="
                            display: inline-block;
                            width: 150px;
                            color: #8492a6;
                            transform: translateY(-11px);
                          "
                          >{{ item.projectCode }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 10px 0 7px;
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          :title="item.projectName"
                          >{{ item.projectName }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 100px;
                            margin: 0 5px 0 0px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.projectCategoryName }}
                        </span>
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.projectTypeName }}
                        </span>
                      </el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目种类：" prop="contractCategory">
                  <el-select
                    :disabled="
                      pageType === 'check' ||
                      contractForm.renew == 1 ||
                      contractForm.contractKind == 1 ||
                      contractForm.contractKind == 2 ||
                      contractForm.contractKind == 3
                    "
                    v-model="contractForm.contractCategory"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in kindList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="项目类型：" prop="contractType">
                  <el-select
                    :disabled="
                      pageType === 'check' ||
                      contractForm.renew == 1 ||
                      contractForm.contractKind == 1 ||
                      contractForm.contractKind == 2 ||
                      contractForm.contractKind == 3
                    "
                    v-model="contractForm.contractType"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in typeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="contractForm.contractKind == 2">
                <el-form-item label="解除原因：" prop="causeDischarge">
                  <el-select
                    v-model="contractForm.causeDischarge"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    :disabled="pageType === 'check'"
                  >
                    <el-option
                      v-for="dict in causeDischargeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="contractForm.contractKind == 0">
                <el-form-item label="合同金额：" prop="contractMoney">
                  <el-input
                    type="Number"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.contractMoney"
                    placeholder="请输入"
                    clearable
                    maxlength="21"
                    class="search-input"
                  >
                    <template #append>万</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  contractForm.contractKind == 1 ||
                  contractForm.contractKind == 2 ||
                  contractForm.contractKind == 3 ||
                  contractForm.renew == 1
                "
              >
                <el-form-item label="原合同金额:" prop="contractMoney">
                  <el-input
                    type="Number"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.contractMoney"
                    placeholder="请输入"
                    clearable
                    maxlength="21"
                    class="search-input"
                    @blur="handleChangePrice"
                  >
                    <template #append>万</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  contractForm.contractKind == 1 ||
                  contractForm.contractKind == 3
                "
              >
                <el-form-item label="变动金额：" prop="changeMoney">
                  <el-input
                    type="Number"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.changeMoney"
                    placeholder="请输入"
                    clearable
                    maxlength="11"
                    class="search-input"
                    @blur="handleChangePrice"
                  >
                    <template #append>万</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  contractForm.contractKind == 1 ||
                  contractForm.contractKind == 3
                "
              >
                <el-form-item
                  label="现合同金额："
                  prop="newContractMoney"
                >
                  <el-input placeholder="请输入"
                    :disabled="pageType === 'check'"
                    type="Number"
                    v-model="contractForm.newContractMoney"
                    disabled
                    clearable
                    maxlength="21"
                    class="search-input"
                  >
                    <template #append>万</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col
                :span="6"
               
              >
                <el-form-item
                  label="是否有预付款："
                  prop="advanceCharge"
                  label-width="120"
                >
                  <el-select
                    :disabled="pageType === 'check'"
                    v-model="contractForm.advanceCharge"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in impleList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="contractForm.advanceCharge == 0">
                <el-form-item label="已收金额：" prop="acceptMoney">
                  <el-input
                    type="Number"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.acceptMoney"
                    placeholder="请输入"
                    clearable
                    maxlength="21"
                    class="search-input"
                  >
                    <template #append>万</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="contractForm.contractKind == 2">
                <el-form-item label="用印文件：" prop="printedDocuments">
                  <el-input
                    type="Number"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.printedDocuments"
                    placeholder="请输入"
                    clearable
                    :min="1"
                    maxlength="10"
                    class="search-input"
                  >
                    <template #append>份</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  contractForm.contractKind == 0 ||
                  contractForm.contractKind == 1 ||
                  contractForm.contractKind == 3
                "
              >
                <el-form-item
                  label="收款银行："
                  :prop="contractForm.advanceCharge == 0 ? 'receiveBank' : ''"
                >
                  <el-input
                  maxlength="50"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.receiveBank"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  contractForm.contractKind == 0 ||
                  contractForm.contractKind == 1 ||
                  contractForm.contractKind == 3
                "
              >
                <el-form-item
                  label="银行账号："
                  :prop="contractForm.advanceCharge == 0 ? 'bankNumber' : ''"
                >
                  <el-input
                    :disabled="pageType === 'check'"
                    v-model="contractForm.bankNumber"
                    placeholder="请输入"
                    clearable
                    maxlength="50"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="签订日期：">
                  <el-date-picker
                    :disabled="pageType === 'check'"
                    v-model="contractForm.signDate"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <template  v-if="[0, 1,3].includes(contractForm.contractKind)">
                <el-col :span="6">
                  <el-form-item label="主要内容：">
                    <el-input
                      :disabled="pageType === 'check'"
                      v-model="contractForm.mainRemark"
                      placeholder="请输入"
                      clearable
                      maxlength="200"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="质保计算标准：">
                    <el-select
                      v-model="contractForm.quantityStandard"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      :disabled="pageType === 'check'"
                    >
                      <el-option
                        v-for="dict in qualityList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="质保起算日：">
                    <el-date-picker
                      :disabled="pageType === 'check'"
                      v-model="contractForm.quantityBegindate"
                      format="YYYY/MM/DD"
                      class="search-input"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="质保到期日：">
                    <el-date-picker
                      :disabled="pageType === 'check'"
                      v-model="contractForm.quantityEnddate"
                      format="YYYY/MM/DD"
                      class="search-input"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                
              </template>
              <!-- <el-col :span="6">
                  <el-form-item label="用印文件：" prop="numberOfCopies">
                    <el-input
                      type="Number"
                      v-model="contractForm.numberOfCopies"
                      placeholder="请输入"
                      clearable
                      :max="99"
                      class="search-input"
                    >
                      <template #append>份</template>
                    </el-input>
                  </el-form-item>
                </el-col> -->
                <el-col :span="6"  v-if="[0, 1,3].includes(contractForm.contractKind)">
                  <el-form-item label="履约保证金：">
                    <el-input
                      :disabled="pageType === 'check'"
                      type="Number"
                      v-model="contractForm.refund"
                      placeholder="请输入"
                      clearable
                      maxlength="21"
                      class="search-input"
                    >
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                
               
                <el-col :span="6">
                  <el-form-item label="应归档份数：" prop="pigeonholeNumber">
                    <el-input
                      v-model="contractForm.pigeonholeNumber"
                      type="Number"
                      placeholder="请输入"
                      clearable
                      :max="99"
                      class="search-input"
                    >
                      <template #append>份</template></el-input
                    >
                  </el-form-item>
                </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="合同备注：">
                  <el-input
                    style="width: 100%"
                    :disabled="pageType === 'check'"
                    v-model="contractForm.remarks"
                    type="textarea"
                    maxlength="200"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="合同附件：" prop="contractAccessory">
                  <Upload
                    :fileList="contractForm.contractAccessory"
                    :limit="10"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    limitation='ciculation'
                    :maxSize="10 * 1024 * 1024"
                    accept=".doc,.docx,.pdf"
                    @success="(result) => uploadSuccess(result)"
                    @deleteFile="(result) => uploadRemove(result)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 添加项目账期计划收款 -->
      <el-collapse-item
        name="2"
        style="position: relative"
        v-if="contactAddShow"
        class="transform-up"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">添加项目账期计划收款</span>
        </template>
        <div class="contract-info">
          <el-form
            :model="contactForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="100px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="项目名称：" prop="projectId">
                  <el-select
                    v-model="contactForm.projectId"
                    style="width: 100%"
                    placeholder="请选择"
                    clearable
                    @change="hangdlerprojectIdchange"
                  >
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">项目编号</span>
                      <span style="margin: 0 80px 0 100px; color: #8492a6"
                        >项目名称</span
                      >
                      <span
                        style="
                          margin: 0 50px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >项目类别</span
                      >
                      <span
                        style="float: right; color: #8492a6; font-size: 13px"
                        >项目类型</span
                      >
                    </el-option>
                    <el-option
                      v-for="item in associationList"
                      :key="item.projectId"
                      :label="item.projectName"
                      :value="item.projectId"
                    >
                      <span style="float: left; color: #8492a6">{{
                        item.projectCode
                      }}</span>
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 10px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        :title="item.projectName"
                        >{{ item.projectName }}</span
                      >
                      <span style="float: right; font-size: 13px">
                        {{ item.projectTypeName }}
                      </span>
                      <span
                        style="
                          float: right;
                          margin: 0 75px 0 0px;
                          font-size: 13px;
                        "
                      >
                        {{ item.projectCategoryName }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="计划账期：" prop="planAccountPeriod">
                  <el-select
                    v-model="contactForm.planAccountPeriod"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handlePlanChange"
                  >
                    <el-option
                      v-for="dict in paymentDaysList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="应收日期：" prop="receivableDate">
                  <el-date-picker
                    v-model="contactForm.receivableDate"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="应收金额："
                  prop="receivableMoney"
                  label-width="120"
                >
                  <el-input
                    v-model="contactForm.receivableMoney"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                    maxlength="21"
                    type="number"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="备注：" prop="remark">
                  <el-input
                    maxlength="2000"
                    v-model="contactForm.remark"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                    @keyup.enter.stop="handleContactAdd(contactFormRef)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 项目账期计划收款 -->
      <el-collapse-item
        v-if="contractForm.contractKind != 2"
        name="3"
        style="position: relative; margin-bottom: 20px"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">项目账期计划收款</span>
          <div
            v-if="
              pageType !== 'detail' && !contactAddShow && pageType !== 'check'
            "
            class="nofixed-search-button button-position"
          >
            <el-button class="btn add" @click.stop="handleContactOperate"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
          <div
            class="nofixed-search-button button-position"
            v-else
            v-if="pageType !== 'detail' && pageType !== 'check'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button class="btn direction" @click.stop="handleContractBack"
              ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
              >关闭</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="contractForm.contractPlanInfoRespVos"
            border
            :height="
              pageType === 'detail' || pageType === 'check'
                ? '100%'
                : contactAddShow
                ? '400px'
                : '180px'
            "
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail' && pageType !== 'check'"
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="项目名称"
              prop="projectName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="计划账期"
              prop="planAccountPeriodName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="应收日期"
              prop="receivableDate"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="应收金额"
              prop="receivableMoney"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="备注"
              prop="remark"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
      <!-- 实收账期信息 -->
      <el-collapse-item
        name="4"
        style="position: relative"
        v-if="
          pageType == 'detail' ||
          (pageType == 'check' && contractForm.contractKind != 2)
        "
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">实收账期信息</span>
          <div
            class="nofixed-search-button button-position"
            v-if="pageType !== 'detail' && pageType !== 'check'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="contractForm.contractActualInfoRespVos"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail'"
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="回款项目"
              prop="projectName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="实收账期"
              prop="actualAccountPeriodName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="实收日期"
              prop="actualDate"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="实收金额"
              prop="actualMoney"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="是否开票"
              prop="isInvoicedName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="开票金额"
              prop="invoiceMoney"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="开票日期"
              prop="invoiceDate"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="备注"
              prop="remark"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
    <!-- 归档默认0 弹窗 -->
    <el-dialog
      :title="title"
      v-model="auditDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="审核备注：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="auditRemark"
          placeholder=""
          type="textarea"
          maxlength="2000"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            v-if="auditResult == 3"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >同意</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 4"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >拒绝</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 6"
            @click="saveCheck()"
            v-loading="loadingCheck"
          >
            驳回</el-button
          >
          <el-button style="background-color: #fff" @click="closeAudit()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 归档1 提交申请人 弹窗 -->
    <el-dialog
      :title="auditDialog1Showtitle"
      v-model="auditDialog1Show"
      width="1000px"
      append-to-body
    >
      <Subapplicant
        v-if="auditDialog1Show"
        @closeauditDialog1="closeauditDialog1"
        @handleBack="handleBack"
        :requestForm="contractForm"
        :modeltype="'contract'"
      ></Subapplicant>
    </el-dialog>
    <!-- 归档2 合同保管员 弹窗 -->
    <el-dialog
      :title="auditDialog2Showtitle"
      v-model="auditDialog2Show"
      width="1000px"
      append-to-body
    >
      <Contractcustodian
        v-if="auditDialog2Show"
        @closeauditDialog2="closeauditDialog2"
        @handleBack="handleBack"
        :requestForm="contractForm"
        :modeltype="'contract'"
      ></Contractcustodian>
    </el-dialog>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import Subapplicant from "../../seal/circulation/subapplicant";
import Contractcustodian from "../../seal/circulation/contractcustodian";
import { getProvinceApi, getnewUserListApi } from "@/api/information/customer";
import {
  addContract,
  editContract,
  getProjectHaveListApi,
  getoldContractListApi,
  getContractDetailApi,
  checkContractApi,
  getCustomerListApi,
} from "@/api/sales/contract";
import { getProjectListApi } from "@/api/sales/project";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  "contractAddShow",
  "update:contractAddShow",
  "refreshList",
]);
const props = defineProps({
  pageType: {
    type: String,
    default: "add",
  },
});
const route = useRoute();
const activeNames = ref(["1", "2", "3", "4"]);
const contractFormRef = ref();
const contactFormRef = ref();
const operateType = ref("");
const detailInfoShow = ref(false);
const refInput = ref();
const refSelect = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 审核状态列表
const checkList = ref([]);
// 合同种类列表
const contractKindList = ref([]);
// 项目种类列表
const kindList = ref([]);
// 是否实施
const impleList = ref([]);
//接触原因列表
const causeDischargeList = ref([]);
// 项目类型列表
const typeList = ref([]);

// 选择审核
const auditDialogShow = ref(false);

let auditDialog1Show = ref(false);
let auditDialog1Showtitle = ref("");
let auditDialog2Show = ref(false);
let auditDialog2Showtitle = ref("");
const loadingCheck = ref(false);
// 项目列表
const projectList = ref([]);
// 原合同列表
const contractList = ref([]);
// 筛选项目列表
const associationList = ref([]);
// 质保列表
const qualityList = ref([]);
// 全部项目列表
const projectAllList = ref([]);
const customerList = ref([]);
let title = ref("");

// 计划账期列表
const paymentDaysList = ref([]);
const provinceValidate = (rule, value, callback) => {
  if (
    !contractForm.value.province ||
    !contractForm.value.city ||
    !contractForm.value.area
  ) {
    callback(new Error("请选择省市区"));
  } else {
    callback();
  }
};
const contractFormTemplate = {
  acceptMoney: null, // 已接收金额
  advanceCharge: null, // 是否预付款
  bankNumber: "", // 银行账号
  checkStatus: null, // 合同审核状态
  contractAccessory: [], // 合同附件上传文件
  contractCategory: null, // 项目分类
  contractKind: null, //合同类型
  contractMoney: null, // 合同金额
  changeMoney: null, //变动金额
  newContractMoney: null, //现合同金额
  contractName: "", // 合同名称
  causeDischarge: null, //解除原因
  oldContractId: null, //原合同
  printedDocuments: null, //用印文件份
  contractPlanInfoRespVos: [], // 账期结算计划收款明细对象
  contractActualInfoRespVos: [],
  contractType: null, // 项目类型
  secondCompanyId: null, // 客户单位
  firstCompanyId: null, // 甲方单位
  implementation: null, // 是否已实施
  projectIds: [], // 关联项目
  receiveBank: "", // 收款银行
  userId: null, // 所属人员
  type: 0, // 按钮类型0：保存；1；提交
  remarks: "", // 合同备注
  signDate: "",
  quantityBegindate: "",
  quantityEnddate: "",
  refund: null,
  mainRemark: "",
  quantityStandard: "",
  renew: "",
};
const contactFormTemplate = {
  contractId: null, // 关联的合同id
  planAccountPeriod: null, // 计划账期
  planAccountPeriodName: "", // 	计划账期中文
  planMoneyId: null, // 未知
  projectId: null, // 关联项目id
  projectName: "", // 关联项目名称
  receivableDate: "", // 应收日期
  receivableMoney: null, // 应收金额
  remark: "", // 	备注
  pigeonholeNumber:null,
  numberOfCopies:null
};

const data = reactive({
  contractForm: JSON.parse(JSON.stringify(contractFormTemplate)),
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  flagList: [
    {
      label: "是",
      value: 1,
    },
    {
      label: "否",
      value: 0,
    },
  ],
  queryRules: {
    numberOfCopies: [
      { required: true, message: "请输入用印文件", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value < 1 || value > 99) {
            callback(new Error("用印份数为0到99之间的整数"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    pigeonholeNumber: [
      { required: true, message: "请输入应归档份数", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value < 1 || value > 99) {
            callback(new Error("应归档份数为0到99之间的整数"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    refund: [
      { required: true, message: "请输入履约保证金", trigger: "blur" },
    ],
    mainRemark: [
      { required: true, message: "请输入主要内容", trigger: "blur" },
    ],
    projectIds: [
      { required: true, message: "请选择关联项目", trigger: "change" },
    ],
    signDate: [
      { required: true, message: "请选择签订日期", trigger: "change" },
    ],
    renew: [
      { required: true, message: "请选择是否续签", trigger: "change" },
    ],
    quantityStandard: [{ required: true, message: "请选择质保计算标准", trigger: "change" }],
    quantityBegindate: [{ required: true, message: "请选择质保起算日", trigger: "change" }],
    quantityEnddate: [{ required: true, message: "请选择质保到期日", trigger: "change" }],
   
    userId: [{ required: true, message: "请选择业务人员", trigger: "change" }],
    firstCompanyId: [
      { required: true, message: "请选择甲方单位", trigger: "change" },
    ],
    secondCompanyId: [
      { required: true, message: "请选择客户单位", trigger: "change" },
    ],
    contractKind: [
      { required: true, message: "请选择合同类型", trigger: "change" },
    ],
    oldContractId: [
      { required: true, message: "请选择原合同", trigger: "change" },
    ],
    contractCategory: [
      { required: true, message: "请选择项目种类", trigger: "change" },
    ],
    causeDischarge: [
      { required: true, message: "请选择解除原因", trigger: "change" },
    ],
    contractType: [
      { required: true, message: "请选择项目类型", trigger: "change" },
    ],
    advanceCharge: [
      { required: true, message: "请选择是否有预付款", trigger: "change" },
    ],
    contractAccessory: [
      { required: true, message: "请选择合同附件", trigger: "change" },
    ],
    changeMoney: [
      { required: true, message: "请输入变动金额", trigger: "blur" },
      {
        pattern: /^-?\d{1,10}(\.\d+)?$/,
        message: "只能输入最多10位数字",
        trigger: "blur",
      },
    ],
    newContractMoney: [
      { required: true, message: "请输入现合同金额", trigger: "blur" },
      {
        pattern: /^\d{1,20}(\.\d+)?$/,
        message: "只能输入最多20位数字",
        trigger: "blur",
      },
    ],
    contractMoney: [
      { required: true, message: "请输入合同金额", trigger: "blur" },
      {
        pattern: /^\d{1,20}(\.\d+)?$/,
        message: "只能输入最多20位数字",
        trigger: "blur",
      },
    ],
    acceptMoney: [
      { required: true, message: "请输入已收金额", trigger: "blur" },
      {
        pattern: /^\d{1,20}(\.\d+)?$/,
        message: "只能输入最多20位数字",
        trigger: "blur",
      },
    ],
    printedDocuments: [
      { required: true, message: "请输入用印文件", trigger: "blur" },
      {
        pattern: /^\d{1,10}(\.\d+)?$/,
        message: "只能输入最多10位数字",
        trigger: "blur",
      },
    ],
    receiveBank: [
      { required: true, message: "请输入收款银行", trigger: "blur" },
      { max: 15, message: "最多可以输入15个字符", trigger: "blur" },
    ],
    bankNumber: [
      { required: true, message: "请输入银行账号", trigger: "blur" },
      { max: 20, message: "最多可以输入20个字符", trigger: "blur" },
    ],
    contractName: [
      { required: true, message: "请输入合同名称", trigger: "blur" },
    ],
  },
  queryContactRules: {
    projectId: [
      { required: true, message: "请选择项目名称", trigger: "change" },
    ],
    planAccountPeriod: [
      { required: true, message: "请选择计划账期", trigger: "change" },
    ],
    receivableDate: [
      { required: true, message: "请选择应收日期", trigger: "change" },
    ],
    receivableMoney: [
      { required: true, message: "请输入应收金额", trigger: "blur" },
      {
        pattern: /^\d{1,20}(\.\d+)?$/,
        message: "只能输入最多20位数字",
        trigger: "blur",
      },
    ],
    remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
  },
  userList: [],
  auditRemark: "",
  auditResult: "",
  applyId: "",
});
const {
  contractForm,
  contactForm,
  queryRules,
  queryContactRules,
  userList,
  auditRemark,
  auditResult,
  applyId,
  flagList,
} = toRefs(data);
const contactAddShow = ref(false);

const handleCheckBtn2 = (requestFormRef, type, title) => {
  if (type == 3) {
    console.log("contractForm", contractForm.value);
    switch (contractForm.value.nextAudit.flowIntype) {
      case "0":
        auditRemark.value = "同意";
        auditResult.value = type;
        applyId.value = contractForm.value.contractId;
        auditDialogShow.value = true;
        loadingCheck.value = false;
        break;
      case "1":
        //提交申请人
        auditDialog1Show.value = true;
        auditDialog1Showtitle.value = "资料归档";
        break;
      case "2":
        //合同保管人
        auditDialog2Show.value = true;
        auditDialog2Showtitle.value = "资料归档";
        break;

      default:
        break;
    }
  } else {
    auditRemark.value = "";
    auditResult.value = type;
    applyId.value = contractForm.value.contractId;
    auditDialogShow.value = true;
    loadingCheck.value = false;
  }
};

const saveCheck = async () => {
  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }

  const obj = {
    checkStatus: auditResult.value,
    contractId: applyId.value,
    auditRemark: auditRemark.value,
    contractKind: contractForm.value.contractKind,
    contractAccessory: contractForm.value.contractAccessory,
  };
  try {
    loadingCheck.value = true;
    const res = await checkContractApi(obj);
    auditDialogShow.value = false;

    //loadingCheck.value =false;

    if (res.code === 200) {
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
    emit("update:contractAddShow", false);
    emit("refreshList", false);
  } catch (error) {
    loadingCheck.value = false;
    emit("update:contractAddShow", false);
    emit("refreshList", false);
    // ElMessage.error(error);
  }
};

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = "";
  applyId.value = "";
  auditDialogShow.value = false;
};

const closeauditDialog1 = () => {
  auditDialog1Show.value = false;
};

const closeauditDialog2 = () => {
  auditDialog2Show.value = false;
};
/**
 * @description: 处理处理合同类型清空其他
 * @param {Number} value 选择值
 */
const handleApplyTypeChange = () => {
  contractForm.value.oldContractId = null;
  contractForm.value.contractCategory = null;
  contractForm.value.contractType = null;
  contractForm.value.causeDischarge = null;
  contractForm.value.advanceCharge = null;
  contractForm.value.newContractMoney = "";
  contractForm.value.changeMoney = "";
  contractForm.value.contractMoney = "";
  contractForm.value.acceptMoney = "";
  contractForm.value.printedDocuments = null;
  contractForm.value.receiveBank = "";
  contractForm.value.bankNumber = "";
  contractForm.value.remarks = "";
  contractForm.value.contractAccessory = [];
  contractForm.value.projectIds = [];
};

const handleRenewChange = (val) => {
  if (val) {
    contractForm.value.contractKind = 0;
  } else {
    contractForm.value.contractKind = null;
  }
};

/**
 * @description: 保存
 * @param {Object} contractFormRef 合同表单引用
 */
const handleAddSave = async (contractFormRef, type) => {
  // if (!contractFormRef) return;
  if (
    contractForm.value.contractPlanInfoRespVos.length == 0 &&
    contractForm.value.contractKind !== 2
  ) {
    ElMessage.error("请添加项目账期计划收款");
    return;
  }
  await contractFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        "确定" + (type == 0 ? "存为草稿" : "提交") + "吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          confirmButtonClass: "confirmBtnClass",
          cancelButtonClass: "cancelBtnClass",
        }
      )
        .then(async () => {
          contractForm.value.type = type;
          // console.log("新增数据", contractForm.value);
          if (!contractForm.value.contractId) {
            const res = await addContract({
              ...contractForm.value,
            });
            if (res.code === 200) {
              emit("update:contractAddShow", false);
              emit("refreshList", false);
              ElMessage.success(res.msg);
              contractForm.value = JSON.parse(
                JSON.stringify(contractFormTemplate)
              );
            } else {
              ElMessage.error(res.msg);
            }
          } else {
            const res = await editContract({
              ...contractForm.value,
            });
            if (res.code === 200) {
              emit("update:contractAddShow", false);
              emit("refreshList", false);
              ElMessage.success(res.msg);
              contractForm.value = JSON.parse(
                JSON.stringify(contractFormTemplate)
              );
            } else {
              ElMessage.error(res.msg);
            }
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("update:contractAddShow", false);
    contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:contractAddShow", false);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      })
      .catch(() => {});
  }
};
/**
 * @description: 处理多选关联项目
 * @param {Number} value 当前值
 */
const handleprojectIdschange = (value) => {
  associationList.value = projectList.value.filter((item) => {
    return value.includes(item.projectId);
  });
  let flag = associationList.value.every((item) => {
    return item.practiceStatus == 3;
  });
  flag
    ? (contractForm.value.implementation = 0)
    : (contractForm.value.implementation = 1);
};
/**
 * @description: 处理原合同
 * @param {Number} value 当前值
 */
const handlecontractschange = (value) => {
  contractForm.value.projectIds = [];
  getProjectHave(value);
  contractList.value.forEach((it) => {
    if (value == it.contractId) {
      contractForm.value.contractPlanInfoRespVos = it.contractPlanInfoRespVos || [];
      contractForm.value.contractCategory = it.contractCategory;
      contractForm.value.contractType = it.contractType;
      contractForm.value.bankNumber = it.bankNumber;
      contractForm.value.receiveBank = it.receiveBank;
      contractForm.value.acceptMoney = it.acceptMoney;
      contractForm.value.advanceCharge = it.advanceCharge;
      contractForm.value.contractMoney = it.contractMoney;
      contractForm.value.remarks = it.remarks;
      contractForm.value.contractAccessory = it.contractAccessory || [];
    }
  });
};
/**
 * @description: 处理多选关联项目
 * @param {Number} value 当前值
 */
const hangdlerprojectIdchange = (value) => {
  associationList.value.forEach((element) => {
    if (element.projectId == value) {
      contactForm.value.projectName = element.projectName;
    }
  });
};
/**
 * @description: 处理业务人员选择
 * @param {Number} value 当前值
 */
const handlePeopleChange = async (value) => {
  contractForm.value.secondCompanyId = null;
  contractForm.value.firstCompanyId = null;
  if (value) {
    await getCustomerListApi(contractForm.value.userId).then((res) => {
      if (res) {
        customerList.value = res;
      }
    });
  } else {
    customerList.value = [];
  }
};

/**
 * @description: 处理计划选择
 * @param {Number} value 当前值
 */
const handlePlanChange = async (value) => {
  contactForm.value.planAccountPeriodName =
    paymentDaysList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid, fields) => {
    if (valid) {
      if (operateType.value === "edit") {
        contractForm.value.contractPlanInfoRespVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
      } else {
        contractForm.value.contractPlanInfoRespVos.push(
          JSON.parse(JSON.stringify({ ...contactForm.value }))
        );
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      contactFormRef.resetFields();
      operateType.value = "add";
      nextTick(() => {
        refInput.value.focus(); // 聚焦
      });
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  contractForm.value.contractAccessory.push({ ...response, businessType: 5 });
}
/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  contractForm.value.contractAccessory.splice(index, 1);
}

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  contactAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
};

/**
 * @description: 处理联系人关闭
 */
const handleContractBack = () => {
  contactAddShow.value = false;
  //   nextTick(() => {
  //     refSelect.value.focus(); // 聚焦
  //   });
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value.focus(); // 聚焦
    });
  } else {
    contractForm.value.contractPlanInfoRespVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getContractDetailApi(id);
    getContract(res.data.contractInfoRespVo.oldContractId);
    contractForm.value = {
      ...res.data.contractInfoRespVo,
      contractPlanInfoRespVos: res.data.contractPlanInfoRespVos,
      contractAccessory: res.data.contractAccessory || [],
      contractActualInfoRespVos: res.data.contractActualInfoRespVos,
      nextAudit: res.data.nextAudit,
      archiveFileList:res.data.archiveFileList || []
    };
    // contractForm.value.oldContractId = contractForm.value.contractName;
    await getCustomerListApi(contractForm.value.userId).then((res) => {
      if (res) {
        customerList.value = res;
      }
    });
    // 所有项目列表
    await getProjectListApi({}, {}).then((res) => {
      if (res.code === 200) {
        projectAllList.value = res.rows;
      }
    });
    let projectArr = [];
    // 项目处理
    projectAllList.value.forEach((item) => {
      // console.log(
      //   "contractForm.value.projectIds",
      //   contractForm.value.projectIds
      // );
      contractForm.value.projectIds.forEach((value) => {
        if (value == item.projectId) {
          projectArr.push(item);
        }
      });
    });
    associationList.value = projectArr;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};
/**
 * @description: 计算变动金额
 * @param {Number} value 选择值
 */
const handleChangePrice = () => {
  // 现合同金额： 原合同金额 + 变动金额
  if (contractForm.value.changeMoney && contractForm.value.contractMoney) {
    contractForm.value.newContractMoney =
      Number(contractForm.value.contractMoney) +
      Number(contractForm.value.changeMoney);
  }
};
/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_contract_check_status").then((res) => {
    // 审核状态
    if (res.code === 200) {
      checkList.value = res.data;
    }
  });

  await getDictsApi("erp_warehousing").then((res) => {
    // 是否实施
    if (res.code === 200) {
      impleList.value = res.data;
    }
  });

  await getDictsApi("erp_cause_discharge").then((res) => {
    // 接触原因
    if (res.code === 200) {
      causeDischargeList.value = res.data;
    }
  });
  await getDictsApi("erp_contract_kind").then((res) => {
    // 合同种类
    if (res.code === 200) {
      contractKindList.value = res.data;
    }
  });
  await getDictsApi("erp_contract_category").then((res) => {
    // 项目种类
    if (res.code === 200) {
      kindList.value = res.data;
    }
  });
  await getDictsApi("erp_contract_type").then((res) => {
    // 项目类型
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
  await getDictsApi("erp_quantity_standard").then((res) => {
    // 质保列表
    if (res.code === 200) {
      qualityList.value = res.data;
    }
  });
  await getDictsApi("erp_account_period").then((res) => {
    // 计划账期
    if (res.code === 200) {
      paymentDaysList.value = res.data;
    }
  });
  await getnewUserListApi({ deptType: 5 }).then((res) => {
    if (res.length > 0) {
      userList.value = res;
    }
  });
  // 项目列表
  await getProjectHaveListApi(contractForm.value.contractId).then((res) => {
    if (res) {
      projectList.value = res;
      projectList.value = projectList.value.filter((item) => {
        return item.checkStatus == 3;
      });
    }
  });
}
async function getProjectHave(contractId) {
  // 项目列表
  await getProjectHaveListApi(contractId).then((res) => {
    // console.log("yuan111", res);
    if (res) {
      projectList.value = res;
      projectList.value = projectList.value.filter((item) => {
        return item.checkStatus == 3;
      });
      projectList.value.forEach((idt) => {
        if (idt.contractId == contractId || idt.currentContract == contractId) {
          contractForm.value.projectIds.push(idt.projectId);
        }
      });
    }
  });
  // handleprojectIdschange(contractForm.value.projectIds)
  handleprojectIdschange(contractForm.value.projectIds);
  if (contractForm.value.projectIds.length) {
    contractFormRef.value.clearValidate("projectIds");
  }
}
async function getContract(oldContractId = null) {
  // 原合同列表
  await getoldContractListApi({}, { oldContractId }).then((res) => {
    console.log("原合同列表");
    console.log(res);
    if (res) {
      if (oldContractId == null) {
        contractList.value = res
          .filter((item) => {
            return item.checkStatus == 3;
          })
          .map((filteredContract) => {
            return {
              ...filteredContract,
              oldContractId: filteredContract.contractId,
            };
          });
      } else {
        contractList.value = res.map((filteredContract) => {
          return {
            ...filteredContract,
            oldContractId: filteredContract.contractId,
          };
        });
      }
      // console.log("projectList.value11", contractList.value);
    }
  });
}
onMounted(() => {
  getDicts();
  if (props.pageType !== "edit") {
    getContract();
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  background-color: #f8faff;
}
:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  width: 268px !important;
  height: 34px !important;
}
.contractAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  .search-input {
    width: 268px;
    height: 34px;
  }
  .contract-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }
  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
}
:deep(.el-input__wrapper) {
  padding: 0px 11px;
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 155px;
  // text-align: center;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
</style>

<style>
.custom-dropdown .dropdown-slot {
  height: 28px;
  line-height: 28px;
}

.custom-dropdown .scrollable-options {
  max-height: 200px; /* 根据需要设置合适的高度 */
  overflow-y: auto;
}
</style>
